<template>
	<el-dialog :close-on-click-modal="false" :title="titleMap[mode]" v-model="visible" :width="600" destroy-on-close
		@closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="100px" label-position="right">
			<el-form-item label="剩余余额:" prop="">
				{{ balance.amount }}
			</el-form-item>
			<el-form-item label="可提现余额:" prop="">
				{{ balance.availableAmount }}
			</el-form-item>
			<el-form-item label="提现金额:" prop="amount">
				<el-input v-model="form.amount" placeholder="请输入提现金额"  />
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">确 认</el-button>
		</template>
	</el-dialog>
</template>

<script>
export default {
	emits: ['success', 'closed'],
	props: {
        balance: { type: Object, default: () => {} },
    },
	data() {
		return {
			mode: "withdraw",
			titleMap: {
				withdraw: '提现申请'
			},
			visible: false,
			isSaveing: false,
			form: {
				id: null,
				amount: 0,
			},
			rules: {
				amount: [
					{ required: true, message: '请输入提现金额', trigger: 'blur' },
					{
						pattern: /^0\.([0-9]|\d[0-9])$|^[0-9]\d{0,8}\.\d{0,2}$|^[0-9]\d{0,8}$/,
						message: "只能输入大于0且最多2位小数的数字",
						trigger: "blur",
					},
				],
			}
		}
	},
	mounted() {
	},
	methods: {
		//显示
		open(mode) {
			if (mode) {
				this.mode = mode
			}
			this.form.amount = 0
			this.visible = true
			return this
		},
		setField(key, val) {
			this.form[key] = val
			return this
		},
		async submit() {
			if (!await this.$refs.dialogForm.validate().catch(() => { return false })) {
                return false
            }

			if (this.form.amount < 0 || this.form.amount == 0) {
				this.$notify.error('提现金额不能小于或等于0')
				return false
			}

			if (this.form.amount > this.balance.availableAmount) {
				this.$notify.error('提现金额不能大于可提现余额')
				return false
			}

			let _data = {
				amount: this.form.amount
			}

			try {
				this.isSaveing = true
				await this.$API.finance.withdrawal.post(_data).then(() => {
					this.visible = false
					this.$emit('success')
					this.$notify.success('申请成功，请等待审核')
				})
			} catch (err) {
				this.isSaveing = false;
			} finally {
				this.isSaveing = false;
			}
		},
	}
}
</script>

